package com.job.interceptor;


import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.job.dao.BaseDao;
import com.job.model.admin.Admin;
import com.job.model.admin.Group;
import com.job.model.admin.Privilege;
import com.job.model.admin.PrivilegePrimaryKey;
import com.job.model.admin.Resource;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class AdminInterCeptor implements Interceptor {
	private BaseDao baseDao;
	private List<Admin> admins;
	private Map<PrivilegePrimaryKey,Privilege> privileges = new HashMap<PrivilegePrimaryKey, Privilege>();
	

	public BaseDao getBaseDao() {
		return baseDao;
	}
	@ javax.annotation.Resource(name="baseDao")
	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	}

	private static final long serialVersionUID = 1L;

	@Override
	public void destroy() {
		System.out.println("destroy");
	}

	@Override
	public void init() {
		System.out.println("---------------------------------------------");
		this.admins=baseDao.searchAllEntity(Admin.class);
		for(Admin admin:admins){
			Set<Group> groupSet = admin.getGroups();
			Iterator<Group> groupIterator = groupSet.iterator();
			while(groupIterator.hasNext()){
				Group group = groupIterator.next();
				Set<Resource> resourceSet = group.getResources();
				Iterator<Resource> resourceIterator = resourceSet.iterator();
				while(resourceIterator.hasNext()){
					Resource resource = resourceIterator.next();
					PrivilegePrimaryKey privilegePrimaryKey = new PrivilegePrimaryKey(group, resource);
					privileges.put(privilegePrimaryKey, baseDao.getById(Privilege.class, privilegePrimaryKey));
				}
			}
		}
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		long startTime = System.currentTimeMillis();
		
		String invoke = invocation.invoke();
		
		System.out.println(invoke);
		
		long endTime = System.currentTimeMillis();
		System.out.println(endTime-startTime);
		return invoke;
	}

}
